/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ClientsFrame;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.table.*;

/**
 *
 * @author Denver A Guitiw
 * @author
 * @author
 */
public class ClientsFrame extends javax.swing.JFrame {
    /**
     * Creates new form ClientsFrame
     */
    public ClientsFrame() {
    	setTitle("Client");
    	initComponents();
        setLocationRelativeTo(null);
    }
    @SuppressWarnings("unchecked")

    public  void enterIPAddress(){
     	try{
     	name = JOptionPane.showInputDialog(ClientFrame,"Enter your name.","ClientName");
     	 ConnectToServer();
     	}
     	 catch (Exception e){
			System.out.println("Error enterIPAddress :  "+e);
			ChatTextArea.append("Error enterIPAddress :  "+e);
			retry++;
			}
     	 if(retry>=10){
				System.out.println("System exit 3");
				System.exit(1);
			}
     }
     public class Listener implements Runnable {  // listener for server

     	public void run(){
     		try{
     		while(( message = in.readLine())!=null){
     			ChatTextArea.append(message.trim()+'\n');
     			}
     		}
     		catch (Exception e){
				System.out.println("Error Listener : "+e);
				retry++;
			}
			if(retry>=10){
				System.out.println("System exit 3");
				System.exit(1);
			}
			enterIPAddress();
			}
     	}

      public  void ConnectToServer(){
    	try {
    	IPaddress = JOptionPane.showInputDialog(ClientFrame,"Enter Server's IP Address.", "192.168.0.0");
    	socket = new Socket(IPaddress, 3339);
    	out = new PrintWriter(socket.getOutputStream(), true);
    	in = new BufferedReader(new InputStreamReader
 							(socket.getInputStream()));
 		new Thread(new listenBroadCast()).start();
 		multisocket = new MulticastSocket(3338);
 		group = InetAddress.getByName("230.0.1.2");
 		multisocket.joinGroup(group);
    	out.println(name);
    	out.println(IPaddress);
    	int row =	Integer.parseInt(in.readLine());
    	int x,y=0;
    	mytable.updateUI();
		BroadCastTextArea.append("Listening BroadCast started"+ '\n');
		message = name+ " has joinded the group";
		broadCast();
    	new Thread(new Listener()).start();
    	new Thread (new acceptFile()).start();

    	}
		catch (Exception e){
			ChatTextArea.append("Error Connecting To Server"+"\n");
		}
    }
	public void sendInfo(){
		try{
			int x,y=0;
		for(x=0;x!=row+1;x++){
    		for(y=0;y!=4;y++){
    			data[x][y] = new DataObject(message =  in.readLine());
    			System.out.println(data[x][y]);
    		}
    	}
		}
		catch (Exception e){
		ChatTextArea.append("Error sending info To Server"+"\n");
		}

	}
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel5 = new javax.swing.JPanel();
        ConnectButton = new javax.swing.JButton();
        OptionButton = new javax.swing.JButton();
        SettingsButton = new javax.swing.JButton();
        DisconnnectButton = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        SendBroadCastButton = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        BroadCastTextArea = new javax.swing.JTextArea();
        BroadCastTextField = new javax.swing.JTextField();
        jPanel9 = new javax.swing.JPanel();
        SendChatTextField = new javax.swing.JTextField();
        SendChatButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        ChatTextArea = new javax.swing.JTextArea();
        SendToUserLabel = new javax.swing.JLabel();
        SendtoUserNameTextField = new javax.swing.JTextField();
		jPanel5.setBorder(BorderFactory.createTitledBorder("User Control"));
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(new java.awt.BorderLayout());

		data = new DataObject[30][4];
      // 	InputData();
        TableModel = new DefaultTableModel();
        mytable = new javax.swing.JTable(TableModel);

        jScrollPane2.setViewportView(mytable);
        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
            .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel4Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
            .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel4Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        ConnectButton.setText("Connect");
        ConnectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConnectButtonActionPerformed(evt);
            }
        });

        OptionButton.setText("Accept");
        OptionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OptionButtonActionPerformed(evt);
            }
        });

        SettingsButton.setText("Send Files");
        SettingsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SettingsButtonActionPerformed(evt);
            }
        });

        DisconnnectButton.setText("Disconnect");
        DisconnnectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DisconnnectButtonActionPerFormde(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(85, 85, 85)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(ConnectButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(2, 2, 2))
                    .addComponent(OptionButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(SettingsButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(DisconnnectButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(95, 95, 95))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addComponent(ConnectButton, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(OptionButton, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(SettingsButton, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
                .addGap(29, 29, 29)
                .addComponent(DisconnnectButton, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                .addGap(48, 48, 48))
        );

        SendBroadCastButton.setText("BroadCast");
        SendBroadCastButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SendBroadCastButtonActionPerformed(evt);
            }
        });

        BroadCastTextArea.setColumns(20);
        BroadCastTextArea.setRows(5);
        jScrollPane4.setViewportView(BroadCastTextArea);

        BroadCastTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BroadCastTextFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(BroadCastTextField)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(SendBroadCastButton)
                .addGap(14, 14, 14))
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(SendBroadCastButton, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
                    .addComponent(BroadCastTextField))
                .addContainerGap())
        );

        SendChatTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SendChatTextFieldActionPerformed(evt);
            }
        });

        SendChatButton.setText("Send");
     	  SendChatButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SendChatButtonActionPerformed(evt);
            }
        });

        ChatTextArea.setColumns(20);
        ChatTextArea.setRows(5);
        jScrollPane3.setViewportView(ChatTextArea);

        SendToUserLabel.setText("Send To:");

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addComponent(jScrollPane3)
                        .addContainerGap())
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addComponent(SendChatTextField)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(SendChatButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(15, 15, 15))
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addComponent(SendToUserLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(SendtoUserNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(263, Short.MAX_VALUE))))
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addComponent(jScrollPane3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(SendToUserLabel)
                    .addComponent(SendtoUserNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(SendChatButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(SendChatTextField)))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 860, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 860, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 536, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void SendChatTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SendChatTextFieldActionPerformed
        // TODO add your handling code here:
        	message = SendChatTextField.getText();
        	SendChatTextField.setText(null);
        	out.println(name+": "+message);
    }//GEN-LAST:event_SendChatTextFieldActionPerformed

	 private void	SendChatButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SendBroadCastButtonActionPerformed
        // TODO add your handling code here:
        	message = SendChatTextField.getText();
        	SendChatTextField.setText(null);
        	out.println(name+": "+message);
    }//GEN-LAST:event_SendChatButtonActionPerforformed

    private void BroadCastTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BroadCastTextFieldActionPerformed
        // TODO add your handling code here:
        	message = BroadCastTextField.getText();
        	broadCast();
        	BroadCastTextField.setText(null);
    }//GEN-LAST:event_BroadCastTextFieldActionPerformed

    private void SendBroadCastButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SendBroadCastButtonActionPerformed
        // TODO add your handling code here:
        	message = BroadCastTextField.getText();
        	broadCast();
        	BroadCastTextField.setText(null);
    }//GEN-LAST:event_SendBroadCastButtonActionPerformed
    private void ConnectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConnectButtonActionPerformed
        // TODO add your handling code here:
        enterIPAddress();
    }//GEN-LAST:event_ConnectButtonActionPerformed
    private void OptionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OptionButtonActionPerformed
        // TODO add your handling code here:
 			try{
				Socket sock = new Socket(IPaddress, 123);
			    byte[] mybytearray = new byte[1024];
			    InputStream is = sock.getInputStream();
			    System.out.println("waiting 2");
			    FileOutputStream fos = new FileOutputStream("FileReceived");
			    BufferedOutputStream bos = new BufferedOutputStream(fos);
			    int ts=  JOptionPane.showConfirmDialog(new JFrame(),"Accept file?");
			    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
			    bos.write(mybytearray, 0, bytesRead);
			   	if(ts==0){
		   		ChatTextArea.append("recieved new file");
		   		sock.close();
		   		fos.close();
		   		bos.close();
		   		is.close();
		   		}
		   		}
		   		catch (Exception e){
		   		}
		   		}//GEN-LAST:event_OptionButtonActionPerformed

    private void SettingsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SettingsButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_SettingsButtonActionPerformed

    private void DisconnnectButtonActionPerFormde(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DisconnnectButtonActionPerFormde
        // TODO add your handling code here:
    }//GEN-LAST:event_DisconnnectButtonActionPerFormde


public  class acceptFile implements Runnable {
 	 	public void run(){
 	 	try{
 	 		while(true){
	 	 		System.out.println("waiting");
				Socket sock = new Socket(IPaddress, 123);
			    byte[] mybytearray = new byte[1024];
			    InputStream is = sock.getInputStream();
			    System.out.println("waiting 2");
			    FileOutputStream fos = new FileOutputStream("FileReceived");
			    BufferedOutputStream bos = new BufferedOutputStream(fos);
			    int ts=  JOptionPane.showConfirmDialog(new JFrame(),"Accept file?");
			    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
			    bos.write(mybytearray, 0, bytesRead);
			   	if(ts==0){
		   		ChatTextArea.append("recieved new file");
		   				}
		   		 	}
	 	 		}
  				catch (Exception e){
	  		}
  		}
    }
 		public void SendFileToClient(){
 		try {
	 	 ServerSocket servsock = new ServerSocket(1234);

		    while (true) {
		      Socket sock = servsock.accept();
		      File myFile = new File("manifest.txt");
		      byte[] mybytearray = new byte[(int) myFile.length()];
		      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
		      bis.read(mybytearray, 0, mybytearray.length);

		      OutputStream os = sock.getOutputStream();
		      os.write(mybytearray, 0, mybytearray.length);
		      os.flush();
		      	sock.close();
		 		}
	 		}
 		catch (IOException e) {
        }
 	}
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientsFrame().setVisible(true);
            }
        });
    }
    	public void broadCast(){ //Sends BroadCast to clients
 		if(multisocket==null){
 			return;
 		}
 		try {
 				message = name+": "+message;
              	System.out.println("broadcasting");
                buf = message.getBytes();
		    	DGsocket = new DatagramSocket();
                packet = new DatagramPacket(buf, buf.length, group, 3338);

               // broadcasting message
                multisocket.send(packet);
                message=null;
   			}
   			catch (IOException e) {
                System.out.println("err: broadCast 10101 "+ e);
            	}
 	}
   	// New thread for listening broadcast
 	public class listenBroadCast implements Runnable{

 		public void run(){
 		try {
        MulticastSocket mcsocket = new MulticastSocket(3338);
        InetAddress address = InetAddress.getByName("230.0.1.2");
		mcsocket.joinGroup(address);

        DatagramPacket packet;
		while(true) {
	    	byte[] buf = new byte[256];
            packet = new DatagramPacket(buf, buf.length);
            mcsocket.receive(packet);

            message = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Quote of the Moment: " + message);
            BroadCastTextArea.append(message + '\n');
		}
            }
   			catch (IOException e) {
                System.out.println("err: listenBroadCast 2101 "+ e);
            	}
 		}
 	}
 	class DefaultTableModel  extends AbstractTableModel {

		   String[] columns = {"Name",
                               "IP Address",
                               "Status",
                               "Message"};
    	public int getColumnCount() {
            return currCol;
        }
		public TableColumn addColumn(TableColumn ob){
			return ob;
		}
        public int getRowCount() {
            return data.length + addrow;
        }
        public String getColumnName(int cols) {
           return columns[cols];
      }
       public Object getValueAt(int rows, int cols) {
            return data[rows][cols];
        }
        public boolean isCellEditable(int row, int col){
        	try{
        		 SelCol=mytable.getSelectedColumn();
        	 	SelRow = mytable.getSelectedRow();
        		SendtoUserNameTextField.setText(mytable.getValueAt(row,0).toString());
            	return false;
        	}catch (Exception e){
        	}
               return false;
        }
        public void setValueAt(Object value, int rows, int cols) {
            if (DEBUG){
                System.out.println("Setting value at " + rows + "," + cols
                                   + " to " + value
                                   + " (an instance of "
                                   + value.getClass() + ")");
            }

          	data[rows][cols] = new DataObject(value);
            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();

            }
        }
        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
   	}
   		public void InputData(){
    	try{
            br = new BufferedReader(new InputStreamReader(fis));
    		fis.close();
    		br.close();

    	}
    	catch (Exception e){
    		System.out.println("Error InputData: "+e);
    		System.out.println("Exception = "+e.getCause());

    	}
		}
	public class DataObject{
		DataObject intevalue,StrValue,ObValue;
		Object value;

		public DataObject(Object value){
			this.value = value;
		}
		public String toString(){
    		return  ("" + value);
    	}
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea BroadCastTextArea;
    private javax.swing.JTextField BroadCastTextField;
    private javax.swing.JTextArea ChatTextArea;
    private javax.swing.JButton ConnectButton;
    private javax.swing.JButton DisconnnectButton;
    private javax.swing.JButton OptionButton;
    private javax.swing.JButton SendBroadCastButton;
    private javax.swing.JButton SendChatButton;
    private javax.swing.JTextField SendChatTextField;
    private javax.swing.JLabel SendToUserLabel;
    private javax.swing.JTextField SendtoUserNameTextField;
    private javax.swing.JButton SettingsButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;


    // End of variables declaration//GEN-END:variables
    	private JFrame optionFrame = new JFrame("Options");
   		private DatagramPacket packet;
		private	DatagramSocket DGsocket = null;
		private	static JFrame frame = new JFrame("Server");
		private Socket socket=null;
		private Socket[] newSocket = new Socket[30];
		private int chatSocketNo=0;
		private String message;
        private ServerSocket serverSocket;
       	private InetAddress group;
       	private MulticastSocket multisocket;
       	private byte[] buf = new byte[256];
       	private	DefaultTableModel TableModel;
       	DataObject[][] data;
    	String name;
		int retry=0;
		String messageFromServer="";
		BufferedReader in = null;
		PrintWriter out;
        boolean isconnect=true;
		int connect=0;
		int listen=0;
		int currCol=4;
		private boolean DEBUG = false;
        InetAddress address;
        Socket[] chatSocket = new Socket[15];
  		String inetadd=null;
      	String IPaddress;
      	private JFrame ClientFrame = new JFrame("Frame");
      	int row = 0;
      	InetAddress inetaddress;
	 	int colmn=0;
      	static JTable mytable;
        int addrow=0;
        int SelRow=0;
        int SelCol=0;
        BufferedReader br;
       	PrintWriter outputstreamTSC;
		BufferedReader 	inTSC;
        String line;
        String SelectedUser="Send to: Username";
		FileInputStream fis;
        String servermessage=null;
		String ClientName=null;
		boolean confirm=true;
 		String ipadd=null;
        String ClientIPadress=null;
        Thread[] thread  = new Thread[75];
    	String ServerUserToClientMessage=null;
    	JFileChooser fc;
    	File file;

}
